<template>
  <div>
    <el-upload
        ref="uploadImg"
        list-type="picture-card"
        :http-request="diyRequest"
        action="#"
        :limit="limit"
        :on-exceed="handleExceed"
        :on-preview="pictureCardPreview"
        :before-remove="removeFileList"
        :on-success="successUpload"
        :show-file-list="showFile"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" width="40%" title="图片预览" show-close>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import {getFileUrl, uploadFile} from "@/api/homeApi";

export default {
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      idCardImgUrls: [],
    }
  },
  props: {
    supportType: {//支持上传文件的格式
      default: () => ['image/jpeg', 'image/jpg', 'image/png'],
      type: Array
    },
    limit: {
      type: Number,
      default: 1
    },
    fileSize: {
      type: Number,
      default: 10
    },
    showFile: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    pictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    removeFileList(file) {
      return new Promise((resolve, reject) => {
        let fileId = file.response.fileId
        this.$confirm(`确定要删除图片${file.name}`, '温馨提示', {
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              let index = this.idCardImgUrls.findIndex(i => i.fileId == fileId)
              this.idCardImgUrls.splice(index, 1)
              this.$emit('setCardPic', this.idCardImgUrls.map(i => i.fileId))
              done()
              resolve()
            } else {
              done()
              reject()
            }
          }
        }).then(() => {}).catch(() => {})
      })
    },
    outSideRemoveFile(index){
      this.idCardImgUrls.splice(index, 1)     
      const files = this.$refs.uploadImg.uploadFiles;
      files.splice(index, 1);
    },
    handleExceed() {
      this.$message.error(`只能上传${this.limit}张图片`)
    },
    /*自定义上传的方法*/
    diyRequest({file, onProgress, onSuccess}) {
      /*对上传图片的大小和格式校验*/
      const isLt = file.size / 1024 / 1024 < this.fileSize
      if (this.supportType.indexOf(file.type) == -1) {
        let supportType = this.supportType
        let msg = ''
        supportType.map(res => {
          msg += res.substring(6) + '/'
        })
        let newMsg = msg.slice(0, (msg.length) - 1)
        this.$message.error(`请上传正确的图片格式！支持的格式有：` + newMsg)
        // 手动触发删除操作
        this.$refs.uploadImg.clearFiles();
        return false;
      }
      if (!isLt) {
        this.$message.error(`上传图片大小不能超过${this.fileSize}MB!`)
        // 手动触发删除操作
        this.$refs.uploadImg.clearFiles();
        return false
      }
      const fileObj = file
      const form = new FormData()
      form.append('file', fileObj)
      form.append('open', true)
      uploadFile(form, (progress) => {
        onProgress(progress)
      }).then(res => {
        if (res.code == 200) {
          let data = {
            imageUrl: `${getFileUrl}${res.data.fileId}`,
            fileName: res.data.fileName,
            fileId: res.data.fileId
          }
          onSuccess({
            name: data.fileName,
            url: data.imageUrl,
            id: data.fileId
          })
          this.idCardImgUrls.push(data)
          this.$emit('setCardPic', this.idCardImgUrls.map(i => i.fileId))
        } else {
          this.$message.error('上传图片失败！')
        }
      }).catch(() => {
        this.$message.error('上传图片失败！')
      })
    },
    successUpload() {
    //   this.$emit('setCardPic', this.idCardImgUrls.map(i => i.fileId))
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/assets/css/element-variables";

:deep(.el-upload) {
  border: 1px dashed $--color-primary;
  border-radius: 0;
}
:deep(.el-upload--picture-card .el-icon-plus) {
  color: $--color-primary !important;
}
</style>

